package org.hq.video.config;

import org.hq.video.component.RsuccessHandler;
import org.hq.video.service.TokenFlterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@ComponentScan(basePackages = "org.hq.video.controller")
@EnableMethodSecurity //基于方法授权
public class SecurityConfig {
    @Autowired
    private TokenFlterService ts;
    @Bean
    public SecurityFilterChain formLoginFilterChain(HttpSecurity http) throws Exception {

        // 登录 配置
        http.formLogin(form -> form
                //表单提交路径
                .loginProcessingUrl("/login")
                //自定义登录页面 无需授权可访问
                .loginPage("/login")
                //登录失败跳转页面
                //.failureUrl("/error")
                //登录成功返回结果
               // .successHandler(new RsuccessHandler())

                //登录成功跳转页面
                .defaultSuccessUrl("/index")
                .permitAll());


        //对请求进行访问控制设置
        http.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
                //设置哪些路径可以直接访问，不需要认证
                .requestMatchers(
                        "/login.html"
                        ,"logintojson"
                        ,"/myuser").permitAll()
                .anyRequest().authenticated() //其他路径的请求都需要认证
        );





        // .formLogin(withDefaults());

        //关闭 csrf
        http.csrf(csrf -> csrf
                //.disable()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                // 忽略登录UR
                .ignoringRequestMatchers("/login")
                .ignoringRequestMatchers("/logintojson")
                .ignoringRequestMatchers("/myuser")
        );







        //配置登录时间
        //http.rememberMe()
        //跨越请求
        http.cors(withDefaults());

        //过来器添加
        // http.addFilterBefore(ts, UsernamePasswordAuthenticationFilter.class);


        return http.build();
    }

}
